import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    List<List<Integer>> ret=new ArrayList<>();

    public List<List<Integer>> permute(int[] nums) {
        List<Integer> list=new ArrayList<>();
        dfs(nums,new boolean[nums.length],list);
        return ret;

    }

    public void dfs(int[] nums,boolean[] vis, List<Integer> list){
        int n=nums.length;
        for(int i=0;i<n;i++){
            boolean[] vis1= Arrays.copyOf(vis,vis.length);

            List<Integer> list1=new ArrayList<>(list);

            if(!vis1[i]){
                list1.add(nums[i]);
                vis1[i]=true;
                if(list1.size()==n){
                    ret.add(list1);
                    return;
                }
                dfs(nums,vis1,list1);
            }
        }




    }
}

//ai优化后的代码
class Solution1 {
    List<List<Integer>> ret = new ArrayList<>();

    public List<List<Integer>> permute(int[] nums) {
        dfs(nums, new boolean[nums.length], new ArrayList<>());
        return ret;
    }

    public void dfs(int[] nums, boolean[] vis, List<Integer> list) {
        if (list.size() == nums.length) {
            ret.add(new ArrayList<>(list)); // 添加当前排列到结果集，这里继续注意要new一个新的出来。
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (!vis[i]) {
                vis[i] = true; // 标记当前数字为已访问
                list.add(nums[i]); // 将当前数字添加到当前排列

                //if (list.size() == nums.length) //不复制不能在这返回还是得回溯，不然影响i+1


                dfs(nums, vis, list); // 递归处理下一个数字

                list.remove(list.size() - 1); // 回溯，移除最后一个数字
                vis[i] = false; // 回溯，取消标记
            }
        }
    }
}



class Solution3 {
    int count=0;
    List<List<Integer>> ret=new ArrayList<>();
    public List<List<Integer>> subsets(int[] nums) {
        dfs(nums,0,new ArrayList());
        return ret;
    }

    public void dfs(int[] nums,int i ,List<Integer> list){
        if(i==nums.length){
            ret.add(new ArrayList(list));
            return;
        }

        dfs(nums,i+1,list);

        list.add(nums[i]);
        dfs(nums,i+1,list);
        list.remove(list.size()-1);


    }
}



class Solution4 {
    List<Integer> list=new ArrayList();
    List<List<Integer>> ret=new ArrayList<>();
    public List<List<Integer>> subsets(int[] nums) {
        dfs(nums,0);
        return ret;
    }

    public void dfs(int[] nums,int i ){
        ret.add(new ArrayList(list));

        for(int j=i;j<nums.length;j++){
            list.add(nums[j]);
            dfs(nums,j+1);
            list.remove(list.size()-1);
        }


    }
}